<?php


namespace app\crm\logic;


use app\crm\model\Leads;
use think\facade\Db;

class LeadsLogic extends AbstractLogic
{


    /**
     * 获取销售新增数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-05 10:50
     */
    public function getNewSalesData($userId,array $request): array
    {
        $data = [
            'name'      => '新增线索',
            'num'       => 0,
            'desc'      => '新增线索转化率',
            'value'     => 0
        ];
        $sqlWhere = '';
        if($request['start_time'] && $request['end_time']){
            $sqlWhere = append_where_sql($sqlWhere,"  create_time BETWEEN " . $request['start_time'] . " AND " . $request['end_time']);
        }
       $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'leads');
        if(in_array(-1,$dataAuthUid)){
            return $data;
        }
        $sqlWhere = !in_array('all',$dataAuthUid) ? append_where_sql($sqlWhere," touch_user_id IN (" . implode(',', $dataAuthUid) . ")") : $sqlWhere;
        $sqlWhere = append_where_sql($sqlWhere,"  touch_user_id !=0");
        $sqlWhere && $sqlWhere = ' where'.$sqlWhere;
        try {
            $sql = "select count(1) new_quantity,sum( CASE WHEN is_transform = 1 THEN 1 ELSE 0  END ) AS total_transform FROM shrimp_crm_leads".$sqlWhere;
            $data = Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data['new_conversion_rate'] = 0;
            $data['new_quantity'] && $data['new_conversion_rate'] =  round($data['total_transform'] / $data['new_quantity'],4) * 100 .'%';
            unset($data['total_transform']);
            $data = [
                'name'      => '新增线索',
                'num'       => $data['new_quantity'],
                'desc'      => '新增线索转化率',
                'value'     => $data['new_conversion_rate']
            ];

        } catch (\Exception $e) {
        }
        return $data;
    }


    /**
     * 获取汇总数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-06 14:23
     */
    public function getSummaryData($userId,array $request): array
    {
        $data = [
            [
                'name'      => '总计',
                'value'     => 0,
            ],
            [
                'name'      => '待处理',
                'value'     => 0,
            ],
            [
                'name'      => '已触达',
                'value'     => 0,
            ],
            [
                'name'      => '无效',
                'value'     => 0,
            ],
        ];
        $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'leads');
        if(in_array(-1,$dataAuthUid)){
            return $data;
        }
        $uidSql = !in_array('all',$dataAuthUid) ? "where touch_user_id IN (" . implode(',', $dataAuthUid) . ") and touch_user_id !=0" : 'where touch_user_id !=0';
        try {
            $sql = "select count(1) total_quantity,sum( CASE WHEN is_transform = 1 THEN 1 ELSE 0  END ) AS total_transform_quantity,sum( CASE WHEN is_transform = 0 THEN 1 ELSE 0  END ) AS total_no_transform_quantity,sum( CASE WHEN is_transform = 3 THEN 1 ELSE 0  END ) AS total_invalid_quantity FROM shrimp_crm_leads ".$uidSql  ;
            $data = Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data = [
                [
                    'name'      => '总计',
                    'value'       => $data['total_quantity'],
                ],
                [
                    'name'      => '待处理',
                    'value'       => $data['total_no_transform_quantity'],
                ],
                [
                    'name'      => '已触达',
                    'value'       => $data['total_transform_quantity'],
                ],
                [
                    'name'      => '无效',
                    'value'       => $data['total_invalid_quantity'],
                ],
            ];

        } catch (\Exception $e) {
        }
        return $data;

    }


    /**
     * 获取消息信息条件
     * @param $request
     * @author Mr.Li
     * @create 2021-08-12 14:09
     */
    protected function getMessageWhere($request)
    {
        $map = [];
        if(isset($request['is_today_allocate']) && $request['is_today_allocate'] ){//今日分配
            array_push($map,['touch_time','>=',strtotime(date('Y-m-d') .' 00:00:00')]);
            array_push($map,['touch_time','<=',strtotime(date('Y-m-d') .' 23:59:59')]);
        }
        if(isset($request['un_finish_time']) && $request['un_finish_time']){//未处理 待进入公海
            if($request['un_finish_time'] == -1){//开关关闭不查询数据
                array_push($map,['leads_id','=',0]);
            }else{
                array_push($map,['touch_time','<=',time() - $request['un_finish_time'] * 86400]);
                array_push($map,['is_transform','in',[0]]);
            }
        }
        array_push($map,['touch_user_id','<>',0]);
        return $map;
    }

    /**
     * 今日分配的线索数量
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 14:55
     */
    public function getMessageNum($userId,array $request): int
    {
        $count = 0;
        $map = $this->getMessageWhere($request);
        try {

            // 获取数据权限UID范围
            $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'leads');

            $count = Leads::where($map)
                ->when(!in_array('all', $dataAuthUid), function($query) use ($userId, $dataAuthUid) {
                    $query->where('touch_user_id', 'in', $dataAuthUid);
                })
               ->count();

        }catch (\Exception $e) {
        }
        return $count;


    }

    /**
     * 线索列表
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 14:55
     */
    public function getMessageList($userId,array $request): array
    {
        $map = $this->getMessageWhere($request);
        $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, 'leads');
        $paginator = Leads::where($map)
            ->when(!in_array('all', $dataAuthUid), function($query) use ($userId, $dataAuthUid) {
                $query->where('touch_user_id', 'in', $dataAuthUid);
            })
            ->field('leads_id,name,source,is_transform,owner_user_id,supply_user_id,create_user_id,touch_user_id,update_time,create_time,last_time,province_id,city_id,county_id,detail_address')
            ->append(['transform_flag'])
            ->order('leads_id desc')
            ->paginate([
                'page'    =>  $request['page']??1,
                'list_rows'   =>  $request['limit']??10
            ]);

        $list = $paginator->getCollection()->toArray();  // 列表
        /*组合查询人员信息*/
        $ownerArr = array_column($list,'owner_user_id');
        $supplyArr = array_column($list,'supply_user_id');
        $createArr = array_column($list,'create_user_id');
        $touchArr = array_column($list,'touch_user_id');
        $userArr = array_values( array_unique( array_filter( array_merge($ownerArr,$supplyArr,$createArr,$touchArr) ) ) );
        $userRows = \app\admin\model\User::where('id','in',$userArr)->field('id,realname')->select()->toArray();
        $userRowsArr = array_column($userRows,'realname','id');
        /*组合查询省市区*/
        $regionIdArr = array_unique( array_merge(array_column($list,'province_id'),array_column($list,'city_id'),array_column($list,'county_id') ) );
        $regionArr = \app\shop\model\Region::where('id','in',$regionIdArr)->field('id,name')->select()->toArray();
        $region = array_column($regionArr,'name','id');
        /*循环处理人员信息*/
        foreach ($list as $k => &$v){
            $v['owner_user'] = $userRowsArr[$v['owner_user_id']]??'';
            $v['supply_user'] = $userRowsArr[$v['supply_user_id']]??'';
            $v['create_user'] = $userRowsArr[$v['create_user_id']]??'';
            $v['touch_user'] = $userRowsArr[$v['touch_user_id']]??'';
            $v['last_time'] = $v['last_time'] != 0 ?date('Y-m-d H:i:s',$v['last_time']):'';
            $v['province']  = $region[$v['province_id']]??'';
            $v['city']      = $region[$v['city_id']]??'';
            $v['county']    = $region[$v['county_id']]??'';
        }

        $permission = get_user_permission_menu($userId,'leads_list_tag');
        $data['menu_list'] = $permission ? $permission : [];
        $data['dataCount'] = $paginator->total();  // 总数
        $data['list'] = $list;
        return $data;
    }


}
